/* ---------------------------------------------------------------------------------------------
 *
 *            Capital Alliance Software Confidential Proprietary
 *            (c) Copyright CAS 201{x}, All Rights Reserved
 *                          www.pekall.com
 *
 * ----------------------------------------------------------------------------------------------
 */
package com.pekall.myDictionary.core;

import java.util.concurrent.ExecutionException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.pekall.myDictionary.utils.Utils;

public abstract class DictSource {
	private static final String TAG = DictSource.class.getSimpleName();

	public interface OnUpdateNotifyListener {
		public static final int FETCH_SUCCESS = 0;
		public static final int NETWORK_ERROR = 1;
		public static final int DATA_FORMAT_ERROR = 2;

		void onEndDownload(int result);
	}

	public DictSource(Context context) {
		mContext = context;
	}

	private int mFetchResult = 0;
	private Message mMessage = new Message();
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (mOnNotifyListener != null) {
				mOnNotifyListener.onEndDownload(mFetchResult);
			}
		}
	};

	public abstract String getUrl(String[] code);

	public abstract Object parseContent(String content);

	public abstract String getSource();

	public boolean specifyEncoding() {
		return false;
	}

	public String getDefaultCharset() {
		return "utf8";
	}

	public void saveContent(String content) {
		String key = mCurrentCode[0].replace(" ", "+");
		String path = "/sdcard/" + "dictionary/" + getSource() + "_" + key;
		FileOperate.WriteData(path, content, false);
	}

	public String getContent() {
		String key = mCurrentCode[0].replace(" ", "+");
		String path = "/sdcard/" + "dictionary/" + getSource() + "_" + key;
		return FileOperate.ReadData(path);
	}

	public String downloadSetContent(String[] code) {
		if (mDownloading)
			return null;

		mCurrentCode = code;
		String content = getContent();
		if (TextUtils.isEmpty(content)) {
			if (!Utils.isNetworkConnected(mContext)) {
				mFetchResult = OnUpdateNotifyListener.NETWORK_ERROR;
			}
			pageTask = new HttpTask();
			pageTask.execute(getUrl(mCurrentCode));
			try {
				content = pageTask.get();
				if (!TextUtils.isEmpty(content)) {
					saveContent(content);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
		// notify the result
		mMessage = Message.obtain(mHandler);
		mHandler.sendMessageDelayed(mMessage, 20);
		mDownloading = false;
		return content;
	}

	class HttpTask extends AsyncTask<String, Integer, String> {
		// 可变长的输入参数，与AsyncTask.exucute()对应
		@Override
		protected String doInBackground(String... params) {
			if (!Utils.isNetworkConnected(mContext)) {
				mFetchResult = OnUpdateNotifyListener.NETWORK_ERROR;
				return null;
			}

			HttpClient httpClient = Utils.createHttpClient(mContext);
			try {
				// 创建 HttpGet 方法，该方法会自动处理 URL 地址的重定向
				HttpGet httpGet = new HttpGet(params[0]);
				HttpResponse response = httpClient.execute(httpGet);
				if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
					// 错误处理，例如可以在该请求正常结束前将其中断
					httpGet.abort();
					mFetchResult = OnUpdateNotifyListener.NETWORK_ERROR;

					return null;
				} else {
					// 读取更多信息
					HttpEntity entity = response.getEntity();
					// String result = specifyEncoding() ?
					// EntityUtils.toString(entity, getDefaultCharset()) :
					// EntityUtils.toString(entity);
					String result = EntityUtils.toString(entity,getDefaultCharset());
					// 返回结果 去掉<em></em>
					String rem = result.replace("&lt;em&gt;", " ");
					String rme = rem.replace("&lt;/em&gt;", " ");
					mFetchResult = OnUpdateNotifyListener.FETCH_SUCCESS;
					return rme;
				}
			} catch (Exception e) {
				e.printStackTrace();
				mFetchResult = OnUpdateNotifyListener.NETWORK_ERROR;

				return null;
			} finally {
				httpClient.getConnectionManager().shutdown();
			}
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(String result) {
			// 返回HTML页面的内容
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			// 任务启动，可以在这里显示一个对话框，这里简单处理
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// 更新进度
			super.onProgressUpdate(values);
			Log.d(TAG, "progress:" + values[0]);
		}
	}

	public void setOnNotifyListener(OnUpdateNotifyListener listener) {
		mOnNotifyListener = listener;
	}

	protected Context mContext;
	private OnUpdateNotifyListener mOnNotifyListener = null;
	private String[] mCurrentCode;
	private boolean mDownloading = false;
	private HttpTask pageTask;
}
